
function selectCell(x, y) {
    const myData = window.myData;
    const cell = myData.farmCells[x][y];
    if (window.actionData.status == "moveAnimal" || window.actionData.status == "moveSingleAnimal") {
        if (window.actionData.moveAnimal == null) {
            if (cell.sheep > 0 || cell.pig > 0 || cell.cattle > 0 || cell.building === "stable") {
                showAnimalSelectionDialog(cell, function (selectedAnimal) {
                    window.actionData.moveAnimal = { x, y, type: selectedAnimal };
                    updateFarmCellForMovingAnimal();
                });
            }
        } else {
            const moveSingle = window.actionData.status == "moveSingleAnimal";
            moveAnimal(x, y, moveSingle);
        }
        return;
    } else if (window.actionData.status == "removeAnimal") {
        removeAnimal(x, y);
        return;
    } else if (window.actionData.status == "buildRooms") {
        if (cell.building != null) {
            return;
        }
        if (hasSubstatus("buildStables")) {
            myData.wood -= 2;
            cell.building = "stable";
            if (cell.pastureIndex === null) {
                window.actionData.usedCells += 1;
            }
        } else {
            myData.reed -= 2;
            if (myData.roomType == "woodenHut") {
                myData.wood -= 5;
            } else if (myData.roomType == "clayHut") {
                myData.clay -= 5;
            } else if (myData.roomType == "stoneHouse") {
                myData.stone -= 5;
            }
            cell.building = myData.roomType;
            window.actionData.newRoomCount += 1;
            window.actionData.usedCells += 1;
        }
        updateFarm();
        updateResourceBar();
        return;
    } else if (window.actionData.status == "plowingFields") {
        if (cell.building != null) {
            return;
        }

        cell.building = "field";
        updateFarm();
        updateResourceBar();
        return;
    } else if (window.actionData.status == "buildingFences") {
        selectCellForFenceBuilding(cell, x, y);
        return;
    } else if (window.actionData.status == "grainUtilization" || window.actionData.status == "sowingSeeds") {
        if (window.actionData.substatus.includes("sowingSeeds") && cell.building === "field") {
            selectCellForSowing(x, y);
            return;
        }
    } else if (window.actionData.status == "farming") {
        if (window.actionData.substatus.includes("plowingFields") && cell.building == null) {
            cell.building = "field";
            updateFarm();
            updateResourceBar();
            return;
        } else if (window.actionData.substatus.includes("sowingSeeds") && cell.building === "field") {
            selectCellForSowing(x, y);
            return;
        }
    } else if (window.actionData.status == "farmRenovation") {
        selectCellForFenceBuilding(cell, x, y);
        return;
    }
}

//------------- 犁田
function selectPlowingFields() {
    if (!confirm('确定选择"犁田"？')) {
        return;
    }

    window.actionData.status = "plowingFields";

    updateAdditionalView();

    window.myData.unusedWorker -= 1;
    updateResourceBar();

    appendWorkerToTitle("plowing-fields");

    dispatchEvent(EVENT_PLOW_FIELD);
}

// 这种方式开启的犁田，不是行动工位提供的，是由卡牌效果提供的额外犁田机会。
async function startPlowingFields() {
    await pushStatusAndWaitNewStatus(async function () {
        window.actionData.status = "plowingFields";
        updateAdditionalView();
    });
}

function endPlowingFields() {
    popStatusOrEndAction();
}

//------------- 运用谷物
async function selectGrainUtilization() {
    if (!confirm('确定选择"运用谷物"？')) {
        return;
    }

    var workSpaceKey = "grain-utilization";
    await dispatchEvent(EVENT_USE_TURN_ACTION_BEFORE, { workSpaceKey });

    window.actionData.status = "grainUtilization";
    window.actionData.substatus = ["bakeBread", "sowingSeeds"];

    updateAdditionalView();

    window.myData.unusedWorker -= 1;
    updateResourceBar();

    // 在标题后追加工人的显示
    appendWorkerToTitle(workSpaceKey);

    dispatchEvent(EVENT_GRAIN_UTILIZATION);
}

function endGrainUtilization() {
    endAction();
}

//------------- 希望增加家庭成员
function selectAddFamilyMember() {
    const totalRooms = countOfRooms();

    if (totalRooms <= window.myData.totalWorkers) {
        alert('你需要有足够的房间来增加家庭成员。');
        return;
    }

    if (!confirm('确定选择"希望增加家庭成员"？')) {
        return;
    }

    window.myData.unusedWorker -= 1;

    addFamilyMember();

    appendWorkerToTitle("add-family-member");

    // 设置状态为打出次要发展卡
    window.actionData.status = "playMinorDevelopmentCard";
    window.actionData.substatus = ["minorDevelopmentCard"];

    updateAdditionalView();
}

function addFamilyMember() {
    window.myData.totalWorkers += 1;
    window.myData.newborns.push(true); // 新增家庭成员为婴儿

    updateResourceBar();

    dispatchEventDelay(EVENT_AFTER_ADD_FAMILY_MEMBER);
}

function endPlayMinorDevelopmentCard() {
    endAction();
}

//------------- 渴望增加家庭成员
function selectDesireAddFamilyMember() {
    if (!confirm('确定选择"渴望增加家庭成员"？')) {
        return;
    }

    window.myData.unusedWorker -= 1;

    addFamilyMember();

    appendWorkerToTitle("desire-add-family-member");
}

//------------- 耕种
function selectFarming() {
    if (!confirm('确定选择"耕种"？')) {
        return;
    }

    window.actionData.status = "farming";
    window.actionData.substatus = ["plowingFields", "sowingSeeds"];

    updateAdditionalView();

    window.myData.unusedWorker -= 1;
    updateResourceBar();

    appendWorkerToTitle("farming");

    dispatchEvent(EVENT_FARMING);
}

function endFarming() {
    endAction();
}

//------------- 职业训练
function selectOccupationTraining(subtype) {
    if (!confirm('确定选择"职业训练"？')) {
        return;
    }

    window.actionData.status = "occupationTraining";
    window.actionData.substatus = ["occupationCard", `subtype${subtype}`];
    updateAdditionalView();

    window.myData.unusedWorker -= 1;
    updateResourceBar();

    appendWorkerToTitle(`occupation-training-${subtype}`);

    dispatchEvent(EVENT_USE_OCCUPATION_TRAINING);
}

function updateOccupationTrainingView() {
    const subtype = window.actionData.occupationTrainingSubtype;
    let promptText = '';

    if (hasSubstatus("subtype1")) {
        promptText = '1食物->1职业卡，第一张职业卡免费。';
    } else if (hasSubstatus("subtype2")) {
        promptText = '2食物->1职业卡，前两张职业卡仅需支付1食物。';
    }

    $(".occupation-training-prompt-view p").text(promptText);
}

function endOccupationTraining() {
    endAction();
}